package cn.wh.system.service.impl;

import cn.wh.basic.service.impl.BaseServiceImpl;
import cn.wh.system.domain.Role;
import cn.wh.system.mapper.RoleMapper;
import cn.wh.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-06-22
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void save(Role role) {
        //保存role表的数据
        roleMapper.save(role);//一定要返回自增Id
        //保存中间表
        initRelationTable(role);
    }
    /**
     * 处理角色关联表的数据
     * @param role
     */
    private void initRelationTable(Role role) {
        //前端要求必须传递最新的全量数据， 我们直接做全量覆盖
        //一：删除历史数据
        roleMapper.removeRoleMenuByRoleId(role.getId());
        roleMapper.removeRolePermissionByRoleId(role.getId());
        //二：保存最新的数据
        //1.保存角色权限表数据
        roleMapper.saveRoleMenu(role);
        //2.保存角色菜单表数据
        roleMapper.saveRolePermission(role);
    }

    @Override
    @Transactional
    public void update(Role role) {
        roleMapper.update(role);
        //保存中间表
        initRelationTable(role);
    }

    @Override
    @Transactional
    public void removeById(Long id) {
        roleMapper.deleteById(id);
        Role role = roleMapper.loadById(id);
        initRelationTable(role);
    }
}

